import request from "./request.js"
import store from '../store/index.js';

// 获取用户信息
function getUserInfo(){
	request.post('merchant/userInfo').then(res=>{
		store.commit('setUserInfo', res);
	})
}
		
// 登录
export const login = (force = false) => {
	let hasLogin = store.state.hasLogin;
	if(hasLogin || force) return true;
	let is_logining = store.state.is_logining;
	if(is_logining) return false;
	store.commit('is_logining', true);
	let token = uni.getStorageSync('token');
	let timeout = uni.getStorageSync('timeout');
	let timestamp = Date.now() / 1000;
	if(token && timestamp<timeout-200) {
		console.log('token：' + token)
		store.commit('login');
		getUserInfo();
	}else{
		var that = this;
		// #ifdef MP-WEIXIN
		wx.login({
			success(res) {
				if (res.code) {
					console.log('code：' + res.code)
					request.post('merchant/login', {
						code: res.code
					}).then(res=>{
						uni.setStorageSync('token', res.token);
						uni.setStorageSync('timeout', res.timeout);
						// 请求获取用户信息
						store.commit('login');
						getUserInfo();
					})
				} else {
					console.log('获取code失败！' + res.errMsg)
				}
			}
		})
		// #endif
	 }
	 store.commit('is_logining', false);
}

export default {
	login
}